package com.qxbb.report.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qxbb.report.Enum.ChainRoleType;
import com.qxbb.report.Enum.LoginUserType;
import com.qxbb.report.bo.BrandBO;
import com.qxbb.report.bo.CommodityBO;
import com.qxbb.report.bo.CommodityInventoryBO;
import com.qxbb.report.bo.InventoryBo;
import com.qxbb.report.dao.*;
import com.qxbb.report.dto.InventoryCommodityDTO;
import com.qxbb.report.dto.InventoryDTO;
import com.qxbb.report.dto.InventoryQuanterDTO;
import com.qxbb.report.dto.InventoryYearDTO;
import com.qxbb.report.pojo.ChainStore;
import com.qxbb.report.pojo.ChainUserInfor;
import com.qxbb.report.service.ChainStoreService;
import com.qxbb.report.utils.StringUtils;
import com.qxbb.report.utils.ZipImgUtils;
import com.qxbb.report.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @author: pebble
 * @data 2023/9/29 16:10
 */
@Service
public class ChainStoreServiceImpl extends ServiceImpl<ChainStoreMapper, ChainStore> implements ChainStoreService {

    @Autowired
    private ChainUserInforMapper chainUserInforMapper;
    @Autowired
    private ChainStoreMapper chainStoreMapper;
    @Autowired
    private ChainStoreGroupElementmMapper chainStoreGroupElementmMapper;
    @Autowired
    private ColorMapper colorMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ZipImgUtils zipImgUtils = new ZipImgUtils();

    @Override
    public List<ChainStoreVO> selectStoreId(Integer userId, Integer userType) {
        if (StringUtils.isNotNull(userId) && StringUtils.isNotNull(userType)) {
            List<ChainStoreVO> storeList = new ArrayList<>();
            // 总部连锁店下拉框
            if (userType == LoginUserType.HEADQUARTERS.getNumber()) {
                storeList = chainStoreMapper.selectAllStore();
                return storeList;
            } else {  // 连锁店经营者下拉框
                ChainUserInfor chainUserInfor = chainUserInforMapper.selectByUserId(userId);  // 查询连锁店用户

                // 判断是否是连锁店经营者
                if (chainUserInfor.getRoleType() == ChainRoleType.CHAIN_STORE_OPERATOR.getRoleType()) {

                    List<Integer> storeIds = chainStoreGroupElementmMapper.selectAllChain(userId);
                    // todo 直营连锁店信息： 位置3 ，共6处
                    if (!storeIds.isEmpty()) { // 查询该连锁店经营者关联店铺
                        for (Integer storeId : storeIds) {
                            ChainStoreVO chainStoreVO = chainStoreMapper.selectChainId(storeId);
                            storeList.add(chainStoreVO);
                        }
                        return storeList;  // 返回该老板所有连锁店信息
                    } else {  // 该连锁店经营者没有关联店铺
                        ChainStoreVO chainStoreVO = chainStoreMapper.selectChainId(chainUserInfor.getChainId());
                        storeList.add(chainStoreVO);
                        return storeList;
                    }
                } else { // 除管理员和督导经营者外其他登录用户
                    ChainStoreVO chainStoreVO = chainStoreMapper.selectChainId(chainUserInfor.getChainId());
                    storeList.add(chainStoreVO);
                    return storeList;
                }
            }
        }
        return null;
    }

    @Override
    public List<InventoryStoreVO> selectInventory(Integer userType, Integer userId) {

        List<InventoryStoreVO> storeList = new ArrayList<>();
        // 总部
        if (userType == LoginUserType.HEADQUARTERS.getNumber()) {
            List<ChainStoreVO> chainStores = chainStoreMapper.selectAllStore();
            for (ChainStoreVO chainStoreVO : chainStores) {
                InventoryStoreVO vo = InventoryStoreVO.builder()
                        .id(chainStoreVO.getValue())
                        .chainName(chainStoreVO.getText())
                        .build();
                storeList.add(vo);
            }

            return storeList;
// 总部进入，先不要获取连锁店的库存，太慢
//            List<Integer> stores = chainStoreMapper.selectAll();
//            for (Integer store : stores) {
//                InventoryStoreVO inventoryStoreVO = chainStoreMapper.selectOneInventoryStore(store);
//                if (StringUtils.isNotNull(inventoryStoreVO)){
//                    storeList.add(inventoryStoreVO);
//                }
//            }
//
//           return storeList.stream().sorted(Comparator.comparing(InventoryStoreVO::getQuantity).reversed()).collect(Collectors.toList());
        } else {  // 连锁店经营者
            ChainUserInfor chainUserInfor = chainUserInforMapper.selectByUserId(userId);  // 查询连锁店用户
            // todo (原判断直营连锁店：位置4 ，共6处）
            // 判断是否是连锁店经营者
            if (chainUserInfor.getRoleType() == ChainRoleType.CHAIN_STORE_OPERATOR.getRoleType()) {
                // 查询groupId
                Integer groupId = chainStoreGroupElementmMapper.selectByChainId(chainUserInfor.getChainId());
                if (StringUtils.isNotNull(groupId)) {
                    // 查询该连锁店经营者关联店铺
                    List<Integer> storeIds = chainStoreGroupElementmMapper.selectByGroupId(groupId);
                    if (!storeIds.isEmpty()) {
                        for (Integer storeId : storeIds) {
                            InventoryStoreVO inventoryStoreVO = chainStoreMapper.selectOneInventoryStore(storeId);
                            if (StringUtils.isNotNull(inventoryStoreVO)) {
                                if (StringUtils.isNull(inventoryStoreVO.getQuantity())) {
                                    inventoryStoreVO.setQuantity(0);
                                }
                                if (StringUtils.isNull(inventoryStoreVO.getCostAmount())) {
                                    inventoryStoreVO.setCostAmount(0.0);
                                }
                                if (StringUtils.isNull(inventoryStoreVO.getSalesAmount())) {
                                    inventoryStoreVO.setSalesAmount(0.0);
                                }
                                storeList.add(inventoryStoreVO);
                            }
                        }
                    }
                    // 返回该老板所有连锁店信息
                    return storeList.stream().sorted(Comparator.comparing(InventoryStoreVO::getQuantity).reversed()).collect(Collectors.toList());
                } else {
                    InventoryStoreVO inventoryStoreVO = chainStoreMapper.selectOneInventoryStore(chainUserInfor.getChainId());
                    if (StringUtils.isNotNull(inventoryStoreVO)) {
                        storeList.add(inventoryStoreVO);
                    }
                    return storeList.stream().sorted(Comparator.comparing(InventoryStoreVO::getQuantity).reversed()).collect(Collectors.toList());
                }

            } else {  // 当前店铺店长 店员
                InventoryStoreVO inventoryStoreVO = chainStoreMapper.selectOneInventoryStore(chainUserInfor.getChainId());
                if (StringUtils.isNotNull(inventoryStoreVO)) {
                    storeList.add(inventoryStoreVO);
                }

                return storeList.stream().sorted(Comparator.comparing(InventoryStoreVO::getQuantity).reversed()).collect(Collectors.toList());
            }
        }
    }

    @Override
    public List<InventoryYearVO> selectInventoryYear(Integer storeId) {
        List<InventoryYearVO> list = new ArrayList<>();
        if (StringUtils.isNotNull(storeId)) {
            List<InventoryYearDTO> brandDTOS = chainStoreMapper.selectByChainId(storeId);
            if (StringUtils.isNotEmpty(brandDTOS)) {
                for (InventoryYearDTO brandDTO : brandDTOS) {
                    InventoryYearVO timeVO = InventoryYearVO.builder()
                            .year(colorMapper.selectYearMsg(brandDTO.getYear()))
                            .quantity(brandDTO.getQuantity())
                            .costAmount(brandDTO.getCostAmount())
                            .salesAmount(brandDTO.getSalesAmount())
                            .build();
                    list.add(timeVO);
                }
            }

        }
        return list.stream().sorted(Comparator.comparing(InventoryYearVO::getQuantity).reversed()).collect(Collectors.toList());
    }

    @Override
    public List<InventoryQuanterVO> selectInventoryQuanter(Integer storeId, String year) {
        List<InventoryQuanterVO> list = new ArrayList<>();
        if (StringUtils.isNotNull(year)) {
            int yearId = colorMapper.selectYearSort(year);
            List<InventoryQuanterDTO> brandDTOS = chainStoreMapper.selectByYearId(storeId, yearId);
            if (StringUtils.isNotEmpty(brandDTOS)) {
                for (InventoryQuanterDTO brandDTO : brandDTOS) {
                    String quanterMsg = colorMapper.selectQuarterMsg(brandDTO.getQuanterId());
                    InventoryQuanterVO timeVO = InventoryQuanterVO.builder()
                            .quanter(quanterMsg)
                            .quantity(brandDTO.getQuantity())
                            .costAmount(brandDTO.getCostAmount())
                            .salesAmount(brandDTO.getSalesAmount())
                            .build();
                    list.add(timeVO);
                }
            }

        }
        return list.stream().sorted(Comparator.comparing(InventoryQuanterVO::getQuantity).reversed()).collect(Collectors.toList());
    }

    @Override
    public List<InventoryBrandVO> selectInventoryBrand(BrandBO brandBO) {
        Integer year = 0; // 年份
        Integer quarter = 0; //季度
        if (StringUtils.isNotNull(brandBO)) {
            year = Integer.valueOf(colorMapper.selectYearSort(brandBO.getYear()));
            quarter = colorMapper.selectQuarterSort(brandBO.getQuanter());
            List<InventoryBrandVO> brandVOList = chainStoreMapper.selectInventoryBrand(year, quarter, brandBO.getStoreId());
            List<InventoryBrandVO> brandVOListNew = new ArrayList<>();
            brandVOList.stream().forEach(inventoryBrandVO -> {
                // 库存成本金额 大于10 和库存数量大于0 的返回
                //if (inventoryBrandVO.getCostAmount() > 10 && inventoryBrandVO.getQuantity() > 0) {
                brandVOListNew.add(inventoryBrandVO);
                //}
            });
            return brandVOListNew.stream().sorted(Comparator.comparing(InventoryBrandVO::getQuantity).reversed()).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public List<InventoryCommodityVO> selectInventoryCommodity(CommodityBO commodityBO) throws IOException {
        List<InventoryCommodityVO> list = new ArrayList<>();
        Integer year = 0; // 年份
        Integer quarter = 0; //季度
        if (StringUtils.isNotNull(commodityBO)) {
            year = Integer.valueOf(colorMapper.selectYearSort(commodityBO.getYear()));
            quarter = colorMapper.selectQuarterSort(commodityBO.getQuanter());
            List<InventoryCommodityDTO> brandVOList = chainStoreMapper.selectInventoryCommodity(year, quarter, commodityBO.getStoreId(), commodityBO.getBrandId());
            if (StringUtils.isNotEmpty(brandVOList)) {

                for (InventoryCommodityDTO inventoryCommodityDTO : brandVOList) {
                    if (inventoryCommodityDTO.getQuantity() == 0 && inventoryCommodityDTO.getCostAmount() < 10)
                        continue;

                    // 查询具体某条商品信息
                    String color = colorMapper.selectColorName(inventoryCommodityDTO.getColorId());
                    if (StringUtils.isNull(color)) {
                        color = "";
                    }
                    //查询品牌
                    String categoryName = categoryMapper.selectCategoryName(inventoryCommodityDTO.getCategoryId());
                    InventoryCommodityVO commodityVO = InventoryCommodityVO.builder()
                            .barcode(inventoryCommodityDTO.getBarcode())
                            .commodityName(inventoryCommodityDTO.getProductCode() + "-" + color + " " + categoryName)
                            .quantity(inventoryCommodityDTO.getQuantity())
                            .costAmount(inventoryCommodityDTO.getCostAmount())
                            .salesAmount(inventoryCommodityDTO.getSalesAmount())
                            .exist(zipImgUtils.picIsExist(inventoryCommodityDTO.getBarcode()))
                            .chainId(inventoryCommodityDTO.getChainId())
                            .build();
                    list.add(commodityVO);
                }
            }
        }
        return list.stream().sorted(Comparator.comparing(InventoryCommodityVO::getQuantity).reversed()).collect(Collectors.toList());
    }

    @Override
    public List<InventoryStoreVO> selectLikeInventory(InventoryBo inventoryBo) {
        List<InventoryStoreVO> storeList = new ArrayList<>();
        // 总部
        if (inventoryBo.getUserType() == LoginUserType.HEADQUARTERS.getNumber()) {
            List<Integer> stores = chainStoreMapper.selectLikeInventory(inventoryBo.getStoreName());
            for (Integer store : stores) {
                InventoryStoreVO inventoryStoreVO = chainStoreMapper.selectOneInventoryStore(store);
                storeList.add(inventoryStoreVO);
            }
            return storeList.stream().sorted(Comparator.comparing(InventoryStoreVO::getQuantity).reversed()).collect(Collectors.toList());
        } else {  // 连锁店经营者
            ChainUserInfor chainUserInfor = chainUserInforMapper.selectByUserId(inventoryBo.getUserId());  // 查询连锁店用户
            // 判断是否是连锁店经营者
            if (chainUserInfor.getRoleType() == ChainRoleType.CHAIN_STORE_OPERATOR.getRoleType()) {
                // 查询groupId
                Integer groupId = chainStoreGroupElementmMapper.selectByChainId(chainUserInfor.getChainId());
                if (StringUtils.isNotNull(groupId)) {
                    // 查询该连锁店经营者关联店铺
                    List<Integer> storeIds = chainStoreGroupElementmMapper.findByLikeAndGroupId(inventoryBo.getStoreName(), groupId);
                    if (!storeIds.isEmpty()) {
                        for (Integer storeId : storeIds) {
                            InventoryStoreVO inventoryStoreVO = chainStoreMapper.selectOneInventoryStore(storeId);
                            storeList.add(inventoryStoreVO);
                        }
                    }
                    // 返回该老板所有连锁店信息
                    return storeList;
                } else {  // 该连锁店经营者没有关联店铺
                    InventoryStoreVO inventoryStoreVO = chainStoreMapper.selectOneInventoryStore(chainUserInfor.getChainId());
                    storeList.add(inventoryStoreVO);
                    return storeList;
                }
            }
        }
        return storeList;
    }

    @Override
    public List<InventoryCategoryVO> selectInventoryCategory(BrandBO brandBO) {
        List<InventoryCategoryVO> list = new ArrayList<>();
        Integer year = 0; // 年份
        Integer quarter = 0; //季度
        if (StringUtils.isNotNull(brandBO)) {
            year = Integer.valueOf(colorMapper.selectYearSort(brandBO.getYear()));
            quarter = colorMapper.selectQuarterSort(brandBO.getQuanter());
            List<InventoryCategoryVO> brandVOList = chainStoreMapper.selectInventoryCategory(year, quarter, brandBO.getStoreId());

            List<InventoryCategoryVO> brandVOListNew = new ArrayList<>();
            brandVOList.stream().forEach(inventoryCategoryVO -> {
                //if (inventoryCategoryVO.getCostAmount() > 10 && inventoryCategoryVO.getQuantity() > 0) {
                brandVOListNew.add(inventoryCategoryVO);
                //}
            });
            return brandVOListNew.stream().sorted(Comparator.comparing(InventoryCategoryVO::getQuantity).reversed()).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public List<InventoryCommodityVO> selectCommodity(CommodityInventoryBO commodityInventoryBO) throws IOException {
        List<InventoryCommodityVO> list = new ArrayList<>();
        Integer year = 0; // 年份
        Integer quarter = 0; //季度
        if (StringUtils.isNotNull(commodityInventoryBO)) {
            year = Integer.valueOf(colorMapper.selectYearSort(commodityInventoryBO.getYear()));
            quarter = colorMapper.selectQuarterSort(commodityInventoryBO.getQuanter());
            List<InventoryDTO> brandVOList = chainStoreMapper.selectInventory(year, quarter, commodityInventoryBO.getStoreId(), commodityInventoryBO.getCategoryId());
            if (StringUtils.isNotEmpty(brandVOList)) {
                for (InventoryDTO inventoryDTO : brandVOList) {
                    if (inventoryDTO.getQuantity() == 0 && inventoryDTO.getCostAmount() < 10)
                        continue;

                    // 查询具体某条商品信息
                    String color = colorMapper.selectColorName(inventoryDTO.getColorId());
                    if (StringUtils.isNull(color)) {
                        color = "";
                    }
                    //查询品牌
                    String brandName = productMapper.selectBrandName(inventoryDTO.getBrandId());
                    InventoryCommodityVO commodityVO = InventoryCommodityVO.builder()
                            .barcode(inventoryDTO.getBarcode())
                            .commodityName(inventoryDTO.getProductCode() + "-" + color + " " + brandName)
                            .quantity(inventoryDTO.getQuantity())
                            .costAmount(inventoryDTO.getCostAmount())
                            .salesAmount(inventoryDTO.getSalesAmount())
                            .exist(zipImgUtils.picIsExist(inventoryDTO.getBarcode()))
                            .chainId(inventoryDTO.getChainId())
                            .build();
                    list.add(commodityVO);
                }
            }
        }
        return list.stream().sorted(Comparator.comparing(InventoryCommodityVO::getQuantity).reversed()).collect(Collectors.toList());
    }

    @Override
    public String selectChainName(Integer storeId) {
        String chainName = chainStoreMapper.selectChainName(storeId);
        // 该连锁店名称是否是依连锁店结尾
        if (chainName.endsWith("连锁店")) {
            chainName = chainName.substring(0, chainName.indexOf("连锁店"));
            return chainName;
        } else {
            return chainName;
        }
    }
}
